package com.lzs.common.service.impl;

import com.lzs.common.config.Constant;
import com.lzs.common.dao.DbFieldDao;
import com.lzs.common.dao.DbTableDao;
import com.lzs.common.dto.table.UpdateByIdDto;
import com.lzs.common.exception.LzsBusinessException;
import com.lzs.common.pojo.common.DbTable;
import com.lzs.common.service.TableService;
import com.lzs.common.vo.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class TableServiceImpl implements TableService {

    @Autowired
    private DbTableDao dbTableDao;

    @Autowired
    private DbFieldDao dbFieldDao;

    /**
     * 根据表名称删除
     * @param tableName
     * @return
     */
    @Override
    public CommonResult deleteByTableName(String tableName) {
        dbTableDao.deleteByTableName(tableName);
        return CommonResult.OK();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public CommonResult<DbTable> getById(String id) {
        DbTable dbTable = dbTableDao.getById(id, Constant.DB_NAME);
        return CommonResult.OK(dbTable);
    }

    /**
     * 根据id修改
     * @param dto
     * @return
     */
    @Override
    public CommonResult updateById(UpdateByIdDto dto) {
        DbTable dbTable = this.getById(dto.getOldTableName()).getObj();
        if (Objects.isNull(dbTable)) {
            throw new LzsBusinessException("表不存在");
        }
        if (StringUtils.isBlank(dto.getNewTableName())){
            dto.setNewTableName(dbTable.getTableName());
        }
        //表名发生变化 修改表名
        if (!dbTable.getTableName().equals(dto.getNewTableName())) {
            dbTableDao.rename(dto.getOldTableName(),dto.getNewTableName());
        }
        //注释发生变化修改表注释
        if (!dbTable.getTableComment().equals(dto.getTableComment())) {
            dbTableDao.updateComment(dto.getNewTableName(), dto.getTableComment());
        }
        return CommonResult.OK();
    }

    @Override
    public CommonResult getAllTable() {
        List<DbTable> tableList = dbTableDao.getAllTable(Constant.DB_NAME);
        return CommonResult.rows(tableList);
    }
}
